<?php
class Nc extends CI_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load->helper(array('url'));
        $this->load->library(array('session', 'r_session', 'form_validation', 'email'));
        $this->r_session->check($this->session->all_userdata());
        $this->load->model(array('sectores_model', 'procesos_model', 'nc_de_model', 'proveedores_model', 'insumos_model', 'tipos_nc_model', 'usuarios_model', 'nc_model', 'derivadas_model'));
    }
    
    public function crear() {
        $session = $this->session->all_userdata();
        $data['sectores'] = $this->sectores_model->get_sectores();
        $data['procesos'] = $this->procesos_model->get_procesos();
        $data['nc_de'] = $this->nc_de_model->get_nc_de();
        $data['proveedores'] = $this->proveedores_model->get_proveedores();
        $data['insumos'] = $this->insumos_model->get_insumos();
        $data['tipos_nc'] = $this->tipos_nc_model->get_tipos_nc();
        $data['usuarios'] = $this->usuarios_model->get_usuarios();
        $data['SID'] = $session['SID'];
        
        $session['title'] = "Ingreso de No Conformidades";
        
        $this->form_validation->set_rules('fecha', 'Fecha', 'required');
        $this->form_validation->set_rules('nc_de', 'NC De', 'required');
        $this->form_validation->set_rules('descripcion', 'Descripción', 'required');
        
        
        if($this->form_validation->run() == FALSE) {
            
        } else {
            $config['upload_path'] = './upload/';
            $config['allowed_types'] = 'gif|jpg|png';
            
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            $size = strlen( $chars );
            $str = '';
            for( $i = 0; $i < 30; $i++ ) {
                    $str .= $chars[ rand( 0, $size - 1 ) ];
            }
            $config['file_name'] = $str;
            
            $this->load->library('upload', $config);
            $nombre_del_campo = 'imagen';
            $data = null;
            if(!$this->upload->do_upload($nombre_del_campo)) {
                $error = array('error' => $this->upload->display_errors());
            } else {
                $data = array('upload_data', $this->upload->data());
            }
            
            $array = array(
                'fecha' => $this->input->post('fecha'),
                'detecto' => $this->input->post('detecto'),
                'derivar' => $this->input->post('derivar'),
                'sector' => $this->input->post('sector'),
                'proceso' => $this->input->post('proceso'),
                'nc_de' => $this->input->post('nc_de'),
                'cantidad' => $this->input->post('cantidad'),
                'insumo' => $this->input->post('insumo'),
                'proveedor' => $this->input->post('proveedor'),
                'remito' => $this->input->post('remito'),
                'lote' => $this->input->post('lote'),
                'IRM' => $this->input->post('IRM'),
                'tipo' => $this->input->post('tipo'),
                'descripcion' => $this->input->post('descripcion'),
                'imagen' => $data[1]['orig_name'],
                'idusuario' => $session['SID'],
                'cerrada' => 0,
                'estado' => 0
            );
            $this->nc_model->set_nc($array);
            
            $usuario_destino = $this->usuarios_model->get_usuario($this->input->post('derivar'));

            $datos['title'] = "No conformidad";
            $from = $session['usuario'];
            $to = $usuario_destino['usuario'];
            $subject = "No Conformidad";
            $body = "<h1>Nueva no conformidad</h1>
                <br>".$session['nombre']." ".$session['apellido']." 
                generó una nueva no conformidad.";
            
            $config['charset'] = 'utf-8';
            $config['wordwrap'] = TRUE;
            $config['mailtype'] = 'html';
            $this->email->initialize($config);

            
            $this->email->from($from, $session['nombre'].' '.$session['apellido']);
            $this->email->to($to);
            $this->email->subject($subject);
            $this->email->message($body);
            
            $this->email->send();
            
            redirect('/nc/crear/', 'refresh');
        }
        $this->load->view('layout/header', $session);
        $this->load->view('nc/crear', $data);
        $this->load->view('layout/footer');
    }
    
    public function abiertas() {
        $session = $this->session->all_userdata();
        $session['title'] = "NC Abiertas";
        $data['nc'] = $this->nc_model->get_nc_abiertas();
        
        
        $this->load->view('layout/header', $session);
        $this->load->view('nc/abiertas', $data);
        $this->load->view('layout/footer');
    }
    
    public function cerradas() {
        $session = $this->session->all_userdata();
        $session['title'] = "NC Cerradas";
        $data['nc'] = $this->nc_model->get_nc_cerradas();
        
        
        $this->load->view('layout/header', $session);
        $this->load->view('nc/cerradas', $data);
        $this->load->view('layout/footer');
    }
    
    public function pdf($id) {
        $data['nc'] = $this->nc_model->get_nc($id);
        $data['nc']['derivada'] = $this->derivadas_model->get_derivada_por_id_nc($data['nc']['idnc']);
        $data['nc']['sector'] = $this->sectores_model->get_sector($data['nc']['sector']);
        $data['nc']['proceso'] = $this->procesos_model->get_proceso($data['nc']['proceso']);
        $data['nc']['proveedor'] = $this->proveedores_model->get_proveedor($data['nc']['proveedor']);
        $data['nc']['insumo'] = $this->insumos_model->get_insumo($data['nc']['insumo']);
        $data['nc']['detecto'] = $this->usuarios_model->get_usuario($data['nc']['detecto']);
        $data['nc']['derivar'] = $this->usuarios_model->get_usuario($data['nc']['derivar']);
        
        
        $this->load->view('nc/pdf', $data);
        
    }
    
    public function todas() {
        $session = $this->session->all_userdata();
        $session['title'] = 'Todas las NC';
        $data['nc'] = $this->nc_model->get_nc();
        
        $this->load->view('layout/header', $session);
        $this->load->view('nc/todas', $data);
        $this->load->view('layout/footer');
        
        
    }
}
?>
